const http = require('http')
const url = require('url')
const { createProxyMiddleware } = require('http-proxy-middleware')

const server = http.createServer((request, response) => {
  if (/^\/api/.test(request.url)) {
    const apiProxy = createProxyMiddleware('/api', {
      // 代理跨域目标接口
      target: 'https://blog.csdn.net',
      changeOrigin: true,
      pathRewrite: {
        '^/api': ''
      },
      // 修改响应头信息，实现跨域并允许带cookie
      onProxyRes: function(proxyRes, req, res) {
        proxyRes.headers['Access-Control-Allow-Origin'] = 'http://127.0.0.1:9000';
        proxyRes.headers['Access-Control-Allow-Credentials'] = 'true';
        proxyRes.headers['Content-Type'] = 'application/json;charset=utf-8';
      },

      // 修改响应信息中的 cookie Domain
      cookieDomainRewrite: 'http://127.0.0.1:9000'  // 可以为false，表示不修改；如下：
      // set-cookie: uuid_tt_dd=10_18756827270-1644377109020-376532; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=.csdn.net;
      // set-cookie: uuid_tt_dd=10_18756827270-1644377157391-106781; Expires=Thu, 01 Jan 2025 00:00:00 GMT; Path=/; Domain=http://127.0.0.1:9000;
    })
    apiProxy(request, response)
  } else {
    switch (url) {
      case '/index.html':
        response.end('index.html')
        break
      case '/search.html':
        response.end('search.html')
        break
      default:
        response.end('404.')
    }
  }
})

server.listen(8080, () => {
  console.log('localhost:8080');
})
